<!-- 1.首先安装vue  国际化电话组件 -->

    <!-- npm install el-phone-number-input; -->

<!--  2.当前页面引入组件 -->

    <!-- import { ElPhoneNumberInput, mobileValidator, phoneNumberValidator} from 'el-phone-number-input' -->

<template>
  <div class="app-container">
    <!-- <el-carousel direction="vertical" :autoplay="true" style="width:100%;" :height="imgHeight">
      <el-carousel-item v-for="material in materials" :key="material.code" style="width:100%;">
        <h3 class="medium">
          <img ref="image" :src="require('' + material.image)" :lazy="true" @click="showForm(material.code)" fit="fit"
            class="banner-img">
        </h3>
      </el-carousel-item>
    </el-carousel> -->
    <!-- <div class="wrap">     </div> -->
    <audio id="audioMusic" class="audio" src="./iphone.mp3" controls autoplay="false" hidden="hidden" ref="audio"></audio>


    <!-- 
    <el-dialog title="商品下单" :visible.sync="visible" width="77%" :close-on-click-modal="true" top="1vh" :center="true"
      :showClose="true"> -->
    <!-- <el-popover
         title="商品选择"
        trigger="manual"
        transition="fade-in-linear"
        visible-arrow="true"
        v-model="visible"> -->

    <!-- <el-button slot="reference" @click="visible = !visible">手动激活</el-button> -->


    <el-row v-if="form.rowColItems.length != 0">
      <el-row v-for="(rowItems, index) in form.rowColItems" :key="index">
        <el-col v-for="(item, materialIndex) in rowItems" :key="item.cmaterialid">
          <el-card :body-style="{ padding: '0px' }" shadow="hover">
            <div>
              <i class="el-icon-shopping-cart-full" style="color: #409EFF;">
                <span style="color: #409EFF">{{ ' ' + item.name + ' ' }} </span>
              </i>
              <el-checkbox v-model="item.checked" style="float: right; padding: 3px 0"
                @click.native="orderCardHandle(item)">
                <!-- <i class="el-icon-success" style="float: right "></i> -->
              </el-checkbox>
              <img lazy="true" :src="require('' + item.image)" class="image" fit="fit" :height="imgHeight">

            </div>


            <!-- <time class="time">{{ currentDate }}</time> -->
            <!-- <el-button type="text" class="button">操作按钮</el-button> -->
            <div class="bottom clearfix">
              <span style="color: #409EFF"> {{ ' ￥单价:' + item.nqtorigtaxprice + '元/' + item.castunitid + ' ' }}

                <el-input-number v-model="item.nnum" :precision="2" :step="0.1" :min="0" :max="1000" placeholder="选购数量"
                  @change="selectTrigger(item.nnum, item.cmaterialid)" size="mini">
                </el-input-number>


              </span>
              <span v-if="item.norigtaxmny != null && item.norigtaxmny > 0" style="color: #409EFF"> {{
                item.norigtaxmny + ' 元' }}
              </span>
            </div>


          </el-card>
        </el-col>
      </el-row>
    </el-row>
    <el-row>
      <el-col>
        <span>

          <el-button type="primary" @click="showOrderPancel()" style="" size="mini">订单信息</el-button>

        </span>
      </el-col>

    </el-row>




    <el-dialog :visible.sync="orderVisible" width="77%" :close-on-click-modal="false" top="10vh" :center="true"
      :showClose="true">
      <div slot="title" class="dialog-title">
        <el-row> <i class="el-icon-edit" style="color: #409EFF;">订单信息</i>
        </el-row>
      </div>


      <!-- 显示勾选的物料信息 -->
      <el-row v-if="form.rowColItems.length != 0">
        <el-row v-for="(rowItems, index) in form.rowColItems" :key="index">

          <el-col v-for="item in rowItems" :key="item.cmaterialid" v-if="item.nnum > 0">
            <i class="el-icon-shopping-bag-1">
              <span style="color: #409EFF">

                {{ '' + item.name + ': ' + item.norigtaxmny + '元 =' + item.nnum + " * " +
                  parseFloat(item.nqtorigtaxprice) }} </span>
            </i>
          </el-col>
        </el-row>

        <el-row v-if="form.ntotalorigmny != null && form.ntotalorigmny > 0">
          <i class="el-icon-s-claim">
            <span style="color: #409EFF">
              {{ '总计: ' + form.ntotalorigmny + '元' }}
            </span></i>
        </el-row>

        <el-row>
          <el-col>
            <el-input placeholder="请输入手机号码" v-model="form.custphone" type="number"
              oninput="if(value.length>11)value=value.slice(0,11)" onkeyup="this.value = this.value.replace(/[^\d]/g,'');"
              class="orderinput">
            </el-input>

          </el-col>
          <el-col style="color: #409EFF; ">
            <el-date-picker v-model="form.bvo[0].dsenddate" type="datetime" placeholder="取货日期"
              :picker-options="pickerOptions" value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm"
              class="orderinput">
            </el-date-picker>
          </el-col>

        </el-row>

        <el-row>
          <el-col>
            <span style="color: #409EFF;"> <el-input v-model="form.desc" type="textarea"
                :autosize="{ minRows: 2, maxRows: 4 }" placeholder="备注" class="orderinput" />
            </span>
          </el-col>
        </el-row>

        <el-row>
          <el-col>
            <el-button type="primary" @click="orderSubmit()" size="mini">提交订单</el-button>
            <i class="el-icon-phone-outline">
              <el-link type="success" href="tel:18312744934">联系我们</el-link></i>

          </el-col>

        </el-row>

      </el-row>

    </el-dialog>

  </div>
</template>
<style>
.orderinput {
  width: 75%;
}

.time {
  font-size: 13px;
  color: #999;
}

.bottom {
  margin-top: 13px;
  line-height: 12px;
}

.button {
  padding: 0;
  float: right;
}

.image {
  width: 100%;
  display: block;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}






/* 走马灯垂直样式 */
.el-carousel__item h3 {
  color: #475669;
  font-size: 14px;
  opacity: 0.75;
  line-height: 100%;
  margin: 0;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n+1) {
  background-color: #d3dce6;
}
</style>

<script>


export default {




  data() {

    return {

      // 图片高度自适应屏幕
      imgHeight: '',
      // 表单对齐方式 顶部
      labelPosition: "left",
      // 弹框 显示 隐藏标记 手动激活
      visible: false,
      orderVisible: false,//有数量 就显示订单提交界面
      // 抽屉框显示 隐藏标记
      drawer: false,
      // 商品展示图
      // urls: [
      //   'http://127.0.0.1:2111/fs/service/uapattachroot/ufiles/94cda926-419d-4c17-bf15-0640d9d754c8?params=KmTyroTfFmOK1_21pKGzAyCiw7TZLNlywSHVZVb0AXEf1tFtgaLmMCmpip8pEInuXLIEqO7pvmkkPNS784PE_7PPPbC4-M_bCeOn6TuQJRmB_7c8rxhbA5YbDKscY6aY-0kzGsUr-ZS4aYyNsuw-nGR2k-QF-VnaEt9UC63W1LCq2sIRFrDwG1Q1SgwZ6z1QCOmE0RZcpUjp_ICE0BEC7A==',
      //           'http://127.0.0.1:2111/fs/service/uapattachroot/ufiles/94cda926-419d-4c17-bf15-0640d9d754c8?params=KmTyroTfFmOK1_21pKGzAyCiw7TZLNlywSHVZVb0AXEf1tFtgaLmMCmpip8pEInuXLIEqO7pvmkkPNS784PE_7PPPbC4-M_bCeOn6TuQJRmB_7c8rxhbA5YbDKscY6aY-0kzGsUr-ZS4aYyNsuw-nGR2k-QF-VnaEt9UC63W1LCq2sIRFrDwG1Q1SgwZ6z1QCOmE0RZcpUjp_ICE0BEC7A==',

      //   'https://fuss10.elemecdn.com/1/34/19aa98b1fcb2781c4fba33d850549jpeg.jpeg',
      //   'https://fuss10.elemecdn.com/0/6f/e35ff375812e6b0020b6b4e8f9583jpeg.jpeg',
      //   'https://fuss10.elemecdn.com/9/bb/e27858e973f5d7d3904835f46abbdjpeg.jpeg',
      //   'https://fuss10.elemecdn.com/d/e6/c4d93a3805b3ce3f323f7974e6f78jpeg.jpeg',
      //   'https://fuss10.elemecdn.com/3/28/bbf893f792f03a54408b3b7a7ebf0jpeg.jpeg',
      //   'https://fuss10.elemecdn.com/2/11/6535bcfb26e4c79b48ddde44f4b6fjpeg.jpeg'
      // ],

      listLoading: false,
      materials: [
        //   { image: 
        // './1001111000000000DQMY.png'
        //   , code: '001', name: '粿条' },
        //  { image: "./1001111000000000DQMY.png", code: '002', name: '豆干' }
      ],

      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '明天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() + 3600 * 1000 * 24);
            picker.$emit('pick', date);
          }
        }, {
          text: '一周后',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 7);
            picker.$emit('pick', date);
          }
        }]
      },
      value1: '',
      value2: '',
      value3: '',
      playAudio: false,
      // 绑定表单校验规则属性



      rules: {
        cmaterialid: [
          // { required: true, message: '请选择商品', trigger: 'blur' },
          { required: true, message: '请选择商品', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        // form.bvo[0].nnum: [
        //   { required: true, message: '请输入数量', trigger: 'blur' },
        // { min: 0.1, max: 1000, message: '请输入>0的数量', trigger: 'blur' }

        // ],
        custphone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { min: 11, max: 11, message: '11位手机号', trigger: 'blur' }
          // { type: 'date', required: true, message: '请选择日期', trigger: 'change' }
        ],
        // date2: [
        //   { type: 'date', required: true, message: '请选择时间', trigger: 'change' }
        // ],
        // type: [
        //   { type: 'array', required: true, message: '请至少选择一个活动性质', trigger: 'change' }
        // ],
        // resource: [
        //   { required: true, message: '请选择活动资源', trigger: 'change' }
        // ],
        // desc: [
        //   { required: true, message: '请填写活动形式', trigger: 'blur' }
        // ]
      }
      ,
      form: {
        ntotalorigmny: '',
        dbilldate: '',
        custphone: '',
        ctrantypeid: "30-01",
        corigcurrencyid: "人民币",
        name: '测试',
        materialID: '',
        // bvo: [{
        //   castunitid: "个",
        //   cmaterialid: "",
        //   nqtorigtaxprice: 0,
        //   nnum: 0,
        //   dsenddate: new Date(),
        // }],
        // 需要空对象 否则界面优先加载代码 v-if="form.rowColItems.length != 0" 会报 _vm.form.rowColItems is undefined"
        rowColItems: [],


        // "data": [
        //   {
        //     "castunitid": "千克",
        //     "code": "01",
        //     "image": "./1001111000000000DQMC.png",
        //     "name": "粿条",
        //     "pk_material": "1001111000000000DQMC",
        //     "price": "2"
        //   },
        //   {
        //     "castunitid": "个",
        //     "code": "02",
        //     "image": "./1001111000000000DQMY.png",
        //     "name": "豆干",
        //     "pk_material": "1001111000000000DQMY",
        //     "price": "1"
        //   }
        // ]


        // materials: [{ idStr: '1', code: '001', name: '粿条' }, { idStr: '2', code: '002', name: '豆干' }],

        date1: '',
        date2: '',
        delivery: false,
        type: [],
        resource: '',
        desc: ''
      }
    }
  },

  created() {
    this.fetchData()
  },
  mounted() {
    // 监听窗口变动大小计算banner高度
    window.addEventListener("resize", () => {
      this.imgLoad()
    });

  },

  methods: {

    chunk(array, size) {
      //获取数组的长度，如果你传入的不是数组，那么获取到的就是undefined
      const length = array.length
      //判断不是数组，或者size没有设置，size小于1，就返回空数组
      if (!length || !size || size < 1) {
        return []
      }
      //核心部分
      let index = 0 //用来表示切割元素的范围start
      let resIndex = 0 //用来递增表示输出数组的下标

      //根据length和size算出输出数组的长度，并且创建它。
      let result = new Array(Math.ceil(length / size))
      //进行循环
      while (index < length) {
        //循环过程中设置result[0]和result[1]的值。该值根据array.slice切割得到。
        result[resIndex++] = array.slice(index, (index += size))
      }
      //输出新数组
      return result
    },
    // ————————————————
    //     版权声明：本文为CSDN博主「智慧的狗狗」的原创文章，遵循CC 4.0 BY - SA版权协议，转载请附上原文出处链接及本声明。
    //     原文链接：https://blog.csdn.net/qq_43427364/article/details/106496362


    // 获取图片的实际长度和宽度
    getImgAttr(url, callback) {

      let img = new Image()
      img.src = url
      callback(img.width, document.documentElement.clientHeight)
      // if (img.complete) {
      //         alert('img.complete' + img.width+"  "+ img.height);

      //   callback(img.width, img.height);
      //   // console.log(img.width, img.height, 'img.width, img.height')
      // } else {
      //      alert(' img.onload fun' + img.width + "  " + img.height);

      //   img.onload = function () {
      //                alert(' img.onload fun exe ????' +  document.documentElement.scrollHeight);

      //     callback(img.width, img.height)
      //     img.onload = null
      //   }
      // }
    },
    imgLoad() {
      this.$nextTick(function () {
        // 定义页面初始的走马灯高度, 默认以第一张图片高度
        if (this.materials.length) {
          this.getImgAttr(this.materials[0].image, (width, height) => {
            // 获取屏宽计算图片容器高度
            let screenWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth
            this.imgHeight = height / width * screenWidth + 'px'
            let screenHeight = document.documentElement.clientHeight;
            screenHeight = screenHeight / 3
            this.imgHeight = screenHeight + 'px'

            // console.log(this.imgHeight, 'this.imgHeight')
          })
        }
      });
    },
    showOrderPancel() {
      this.orderVisible = true;
    },
    /**
     * 
     * @param {数量} number 
     * @param {物料id匹配} materialID 
     */
    selectTrigger(number, materialID) {
      console.debug('selectTrigger ' + number + ' ' + materialID);
      // for (let i = 0; i < this.form.rowItems.length; i++) {
      //   if (this.form.rowItems[i].code == materialID) {
      //     this.form.bvo[0].nqtorigtaxprice = this.materials[i].price

      //     this.form.bvo[0].castunitid = this.materials[i].castunitid;

      //   }
      // }
      this.form.ntotalorigmny = 0;
      var orderVisible = false;
      this.form.rowColItems.forEach(rowColItem => {
        rowColItem.forEach(item => {

          if (item.nnum == null) {
            item.nnum = 0;
          }
          if (item.nnum > 0) {
            item.checked = true;
            orderVisible = true;
          } else {
            item.checked = false;
          }
          // item.norigtaxmny = (Number.parseFloat(item.nnum) * Number.parseFloat(item.nqtorigtaxprice)).toFixed(2);

          item.norigtaxmny = this.accMul(item.nnum, item.nqtorigtaxprice);

          console.debug("  item.norigtaxmny:" + item.norigtaxmny)
          this.form.ntotalorigmny = this.accAdd(item.norigtaxmny, this.form.ntotalorigmny);

          console.debug("   this.form.ntotalorigmny:" + this.form.ntotalorigmny)

        });
      });


      // if (number == "") {
      //   number = 0;
      // }

    },
    // 物料卡片未被勾选清除金额信息 传入的对象无法影响this中的数据 即this.form.rowColItems
    orderCardHandle(material) {

      console.debug('check' + material.checked);
      if (material.checked) {
        this.form.ntotalorigmny = this.accSub(this.form.ntotalorigmny, material.norigtaxmny);

        material.nnum = 0;
        material.norigtaxmny = 0;

        // this.form.rowColItems.forEach(rowColItem => {
        //   rowColItem.forEach(item => {
        //     if (item.cmaterialid == material.cmaterialid) {
        //       item.nnum = 0;

        //     }
        //   });
        // });

      }
    },

    orderSubmit() {
      const formatter = new Intl.DateTimeFormat('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
      this.form.bvo.forEach(item => {
        if (item.dsenddate instanceof Date) {
          item.dsenddate = formatter.format(item.dsenddate);
        }
        debugger;

        item.nnum = item.nnum.toFixed(2);
      });
      // let orderForm = this.form.rowColItems.flat();
      // this.form.bvo = orderForm;
      debugger;
      this.$store.dispatch('order/addOrder', this.form).then(() => {
        this.listLoading = false
        this.$message('订单已成功提交商家!');
        localStorage.setItem('custphone', this.form.custphone)
      }).catch(() => {
        this.listLoading = false
      })

      // debugger
      // 点击创建触发提示音
      this.playAudio = true;
      this.playMusic();
      this.playAudio = false;

    },

    onSubmit(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          this.listLoading = true;
          if (this.form.bvo[0].dsenddate instanceof Date) {

            const formatter = new Intl.DateTimeFormat('zh-CN', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit',
              hour: '2-digit',
              minute: '2-digit',
              second: '2-digit'
            });
            this.form.bvo[0].dsenddate = formatter.format(this.form.bvo[0].dsenddate);
          }


          this.$store.dispatch('order/addOrder', this.form).then(() => {
            this.listLoading = false
            this.$message('订单已成功提交商家!');

          }).catch(() => {
            this.listLoading = false
          })
          // 点击创建触发提示音
          this.playAudio = true;
          this.playMusic();
          this.playAudio = false;
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },



    // this.$store.dispatch('order/createOrder', this.form).then(() => {
    //         this.$message('submit!');
    //    this.loading = false
    // }).catch(() => {
    //   this.loading = false
    // })

    showForm(code) {
      this.visible = !this.visible;
      // this.form.bvo[0].cmaterialid = code;

      // this.materials.forEach(item => {

      //   if (item.code == code) {
      //     this.form.bvo[0].nqtorigtaxprice = item.price;
      //     this.form.bvo[0].castunitid = item.castunitid;

      //   }
      // });

    },
    onCancel() {

    },

    fetchData() {
      this.listLoading = false
      this.$store.dispatch('order/getMaterial', { "materialClass": "02" }).then(response => {
        this.materials = response.data;
        var bvo = [];
        this.materials.forEach(item => {
          // 图片框选购买数量时标记勾选物料
          // norigtaxmny 价税合计 nqtorigtaxprice danjia
          let material = {
            castunitid: item.castunitid, cmaterialid: item.code, nqtorigtaxprice: item.price, norigtaxmny: 0,
            nnum: 0, image: item.image, name: item.name, checked: false, dsenddate: new Date(),
          }

          bvo.push(material);
        });
        /**
         * 后台接口data bvo
         */
        this.form.bvo = bvo;
        this.form.custphone = localStorage.getItem('custphone');


        let items = this.chunk(this.form.bvo, 2);
        /**
         * 界面显示指定行列的data rowColItems
         */
        this.form.rowColItems = items;
        this.listLoading = false
        this.imgLoad();

        // [{
        //   castunitid: "个",
        //   cmaterialid: "",
        //   nqtorigtaxprice: 0,
        //   nnum: 0,
        //   dsenddate: new Date(),
        // }],
        // "data": [
        //   {
        //     "castunitid": "千克",
        //     "code": "01",
        //     "image": "./1001111000000000DQMC.png",
        //     "name": "粿条",
        //     "pk_material": "1001111000000000DQMC",
        //     "price": "2"
        //   },
        //   {
        //     "castunitid": "个",
        //     "code": "02",
        //     "image": "./1001111000000000DQMY.png",
        //     "name": "豆干",
        //     "pk_material": "1001111000000000DQMY",
        //     "price": "1"
        //   }
        // ]


      })
    },
    playMusic() {
      //获取音频元素audioMusic play播放提示音
      if (this.playAudio) {
        document.getElementById('audioMusic').play();
      }

    },
    /**
     * @param {*} arg1 数字
     * @param {*} arg2 数字
     * @description 两数字相乘 保持精度
     */
    accMul(arg1, arg2) {
      let m = 0;
      const s1 = arg1.toString();
      const s2 = arg2.toString();
      try {
        m += s1.split(".")[1].length;
      } catch (e) { }
      try {
        m += s2.split(".")[1].length;
      } catch (e) { }
      return (
        (Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) /
        Math.pow(10, m)
      );
    },
    /**
     * @param {*} arg1 数字
     * @param {*} arg2 数字
     * @description 两数字相加 保持精度
     */
    accAdd(arg1, arg2) {
      let r1, r2, m;
      try {
        r1 = arg1.toString().split(".")[1].length;
      } catch (e) {
        r1 = 0;
      }
      try {
        r2 = arg2.toString().split(".")[1].length;
      } catch (e) {
        r2 = 0;
      }
      m = Math.pow(10, Math.max(r1, r2));
      return (arg1 * m + arg2 * m) / m;
    },

    /**
     * @param {*} arg1 数字
     * @param {*} arg2 数字
     * @description 两数字相减 保持精度
     */
    accSub(arg1, arg2) {
      let r1, r2, m, n;
      try {
        r1 = arg1.toString().split(".")[1].length;
      } catch (e) {
        r1 = 0;
      }
      try {
        r2 = arg2.toString().split(".")[1].length;
      } catch (e) {
        r2 = 0;
      }
      m = Math.pow(10, Math.max(r1, r2));
      n = r1 >= r2 ? r1 : r2;
      return ((arg1 * m - arg2 * m) / m).toFixed(n);
    }
    ,
    /**
     * @param {*} arg1 数字
     * @param {*} arg2 数字
     * @description 两数字相除 保持精度
     */
    accDiv(arg1, arg2) {
      let t1 = 0;
      let t2 = 0;
      let r1, r2;
      try {
        t1 = arg1.toString().split(".")[1].length;
      } catch (e) { }
      try {
        t2 = arg2.toString().split(".")[1].length;
      } catch (e) { }
      r1 = Number(arg1.toString().replace(".", ""));
      r2 = Number(arg2.toString().replace(".", ""));
      let intDiv = r1 / r2;
      let pow = Math.pow(10, t2 - t1);
      return accMul(intDiv, pow); // 这里用上面定义好的乘法运算
    },

  }
}
</script>



